package com.sys.utils;

import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class ConfigWriter {
    // 遍历的顺序，与放入的顺序是一致的
    private Map<String,String> map = new LinkedHashMap<>();


    public void put(String key,String value){
        map.put(key,value);
    }

    public void save(String fileName,String charset) throws IOException {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            fos = new FileOutputStream(fileName);
            osw = new OutputStreamWriter(fos,charset);
            bw = new BufferedWriter(osw);
            // 将map中数据全出来
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for( Map.Entry<String, String> item : entries ){
                String key = item.getKey();
                String value = item.getValue();
//                System.out.println(key+":"+value);
                bw.write(key+"="+value);
                bw.newLine();
            }


        } catch (FileNotFoundException e) {
            throw e;
        } catch (UnsupportedEncodingException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        }finally {
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    throw e;
                }
            }
            if(osw!=null){
                try {
                    osw.close();
                } catch (IOException e) {
                    throw e;
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
    }
}
